var AjaxCrud = QualityCheck.AjaxCRUD;
var serverUrl = QualityCheck.GPUD.ServiceConfig;
var currentPage = 1;
//var pageSize = 10;
var map = null;
var toolbar = null;
var scale = null;
var pointMarker = {};//轨迹点对象
var cluster = null;
var cachedatas = null;
$(function(){
	var usercode = $("#user-name",parent.parent.document).attr("code");
	var userkey = $("#user-name",parent.parent.document).attr("key");
	var usertype = $("#user-name",parent.parent.document).attr("usertype");
	keyCheck(usercode,usertype,userkey,function(){
		initPages();
		window.onresize = function () {
			initPages();
		};
		pageBtns();
		initMap();
		initClass();
	});
});
function initMap(){
	map = new AMap.Map("map",{
		level:15,//设置地图缩放级别
	});
	map.plugin(["AMap.ToolBar","AMap.OverView","AMap.Scale"],function(){ 
		toolbar = new AMap.ToolBar();
		toolbar.autoPosition=false; //加载工具条 
		map.addControl(toolbar);  	
		scale = new AMap.Scale(); //加载比例尺
		map.addControl(scale);
	});
	map.setDefaultCursor("url(http://developer.amap.com/wp-content/uploads/2014/06/closedhand.cur),pointer");
	$(".amap-logo").hide();
	$(".amap-copyright").hide();
	$(".amap-container").css("position","absolute");
	getNowCity();
}
function getNowCity(){
	  //加载城市查询插件
  AMap.service(["AMap.CitySearch"], function() {
      //实例化城市查询类
      var citysearch = new AMap.CitySearch();
      //自动获取用户IP，返回当前城市
      citysearch.getLocalCity(function(status, result) {
          if (status === 'complete' && result.info === 'OK') {
              if (result && result.city && result.bounds) {
                  var citybounds = result.bounds;
                  //地图显示当前城市
                  map.panTo(new AMap.LngLat(citybounds.getCenter().lng,citybounds.getCenter().lat));
              }
          }
      });
  });
}
function initClass(){
	var userKey = $("#user-name",parent.parent.document).attr("key");
	var userRoles = $("#user-name",parent.parent.document).attr("rolecodes");
	var data = {
			cmd:"getDataRole",
			model:"license",
			userKey:userKey,
			data:{
				rolecode:userRoles
			},
			remark:"",
	};
	AjaxCrud.get(serverUrl.ServerLoginUrl,data,function(res){
		var typeOpt = "";
		var gradeOpt = "";
		if(res.result == 1 && res.data != undefined && res.data != ""){
			var data = res.data;
			for(var i = 0; i < data.length; i++){
				var name = "";
				if(data[i].type == "0"){
					name = "幼儿园";
				}else if(data[i].type == "1"){
					name = "小学";
				}else if(data[i].type == "2"){
					name = "中学";
				}else if(data[i].type == "3"){
					name = "高中";
				}
				typeOpt += "<option value='"+data[i].type+"'>"+name+"</option>";
			}
			$("#type-position").html(typeOpt);
			
			var gradeData = data[0].data;
			for(var i = 0; i < gradeData.length; i++){
				gradeOpt += "<option value='"+gradeData[i].grade+"' classcodes='"+gradeData[i].classcode+"' classes='"+gradeData[i].classes+"'>"+gradeData[i].grade+"年级</option>";
			}
			$("#grade-position").html(gradeOpt);
			
			var classes = $("#grade-position option:selected").attr("classes").split(",");
			var classcodes = $("#grade-position option:selected").attr("classcodes").split(",");
			var classOpt = "";
			for(var j = 0; j < classes.length; j++){
				classOpt += "<option value='"+classcodes[j]+"' classes='"+classes[j]+"'>"+classes[j]+"班</option>";
			}
			$("#class-position").html(classOpt);
			
			$("#type-position").unbind("change");
			$("#type-position").change(function(){
				var gradeData = null;
				var type = $("#type-position option:selected").val();
				var gradeOpt = "";
				if(type != ""){
					for(var i = 0; i < data.length; i++){
						if(data[i].type == type){
							gradeData = data[i].data;
						}
					}
					for(var i = 0; i < gradeData.length; i++){
						gradeOpt += "<option value='"+gradeData[i].grade+"' classcodes='"+gradeData[i].classcode+"' classes='"+gradeData[i].classes+"'>"+gradeData[i].grade+"年级</option>";
					}
				}
				$("#grade-position").html(gradeOpt);
				
				var classes = $("#grade-position option:selected").attr("classes").split(",");
				var classcodes = $("#grade-position option:selected").attr("classcodes").split(",");
				var classOpt = "";
				for(var j = 0; j < classes.length; j++){
					classOpt += "<option value='"+classcodes[j]+"' classes='"+classes[j]+"'>"+classes[j]+"班</option>";
				}
				$("#class-position").html(classOpt);
				getStudentsByClassCode(1);
			});
			
			$("#grade-position").unbind("change");
			$("#grade-position").change(function(){
				var classes = $("#grade-position option:selected").attr("classes").split(",");
				var classcodes = $("#grade-position option:selected").attr("classcodes").split(",");
				var classOpt = "";
				for(var j = 0; j < classes.length; j++){
					if(classcodes[j] == "" && classes[j] == ""){
						classOpt += "<option value='' classes=''>班级</option>";
					}else{
						classOpt += "<option value='"+classcodes[j]+"' classes='"+classes[j]+"'>"+classes[j]+"班</option>";
					}
				}
				$("#class-position").html(classOpt);
				getStudentsByClassCode(1);
			});
			
			$("#class-position").unbind("change");
			$("#class-position").change(function(){
				getStudentsByClassCode(1);
			});
		}else{
			
		}
		getStudentsByClassCode(1);
	},null,null);
}
//function pageData(data,currentpage,pagesize){
//	var start = (currentpage-1)*pagesize;
//	var end = currentpage*pagesize-1;
//	var datas = data.slice(start,end);
//	return datas;
//};
function getStudentsByClassCode(currentpage){
	processBegin("数据加载中······");
	var userKey = $("#user-name",parent.parent.document).attr("key");
	var userRoles = $("#user-name",parent.parent.document).attr("rolecodes");
	var schoolcode = $("#user-name",parent.parent.document).attr("schoolcode");
	var classcode = $("#class-position option:selected").val();
	var type = $("#type-position option:selected").val();
	var data = {
			cmd:"teacherGetStudentsPosition",
			model:"position",
			userKey:userKey,
			data:{
				rolecode:userRoles,
				classcode:classcode,
				schoolcode:schoolcode,
//				currentpage:currentpage,
//				pageSize:10,
				schooltype:type
			},
			remark:""
	};
	AjaxCrud.get2(serverUrl.ServerLoginUrl,data,function(res){
		map.clearInfoWindow();
		//cachedatas = res;
		initStudentTable(currentpage,res);
		if(res.result == 1 && res.data != undefined && res.data != ""){
			var list = res.data;
			markers = [];
			for(var i = 0; i < list.length; i++){
				if(list[i].lonLat != undefined && list[i].lonLat != null){
					var pointArr = list[i].lonLat.split(",");
					var y = pointArr[0];
					var x = pointArr[1];
					var showObj = {};
					showObj["学生"] = list[i].studentname;
					showObj["IMEI"] = list[i].imei;
					showObj["数据时间"] = list[i].time;
					if(list[i].address != null){
						showObj["当前位置"] = list[i].address;
					}else{
						showObj["当前位置"] = "暂时不能定位到准确地点";
					}
					var imgUrl = "";
					if(list[i].type == 0 || list[i].type == "0"){
						imgUrl = '../../../../img/position/lixian.png';
						showObj["定位方式"] = "离线";
					}else if(list[i].type == 1 || list[i].type == "1"){
						imgUrl = '../../../../img/position/beidou.png';
						showObj["定位方式"] = "北斗定位";
					}else if(list[i].type == 2 || list[i].type == "2"){
						imgUrl = '../../../../img/position/shinei.png';
						showObj["定位方式"] = "蓝牙定位";
						var roomD = JSON.parse(list[i].remark);
						showObj["室内地图"] = "<a href='javascript:void(0);' onClick=\"enterRoom('"+roomD.scale+"','"+roomD.x+"','"+roomD.y+"','"+roomD.build_name + roomD.floor+"','"+roomD.build_id+"','"+roomD.floor+"','"+showObj["学生"]+"','"+showObj["手机"]+"');\" class='enter-room'>进入</a>";
					}else if(list[i].type == 3 || list[i].type == "3"){
						imgUrl = '../../../../img/position/jizhan.png';
						showObj["定位方式"] = "基站定位";
					}
					showObj["终端电量"] = "<img src='../../../../img/position/power_"+ list[i].power +".png' style='padding-top:5px;'/>";
					var icon = new AMap.Icon({
						size:new AMap.Size(40,40),//图标大小
						image:imgUrl,//大图地址
						imageSize:new AMap.Size(40,40)
					});
					addMarker(x,y,icon,showObj,list[i].studentcode);
					map.panTo(new AMap.LngLat(y,x));
					
				}
			}
			if (cluster) {
		        cluster.setMap(null);
		    }
			map.plugin(["AMap.MarkerClusterer"], function () {
				cluster = new AMap.MarkerClusterer(map, markers);
	        });
		}
	},null,null);
}
function initStudentTable(currentpage,res){
	currentPage = currentpage;
	//var res = cachedatas;
	var content = "";
	if(res.result == 1){
		if(res.data != undefined && res.data != ""){
			var data = res.data;
//			var total = res.data.length;
//			totalPage = Math.ceil(total/pageSize);
//			$("#total-page").text(totalPage);
//			$("#now-page").text(currentpage);
			if(data.length > 0){
				for(var i = 0; i < data.length; i++){
					for(var key in data[i]){
						if(data[i][key] == null || data[i][key] == undefined){
							data[i][key] = "";
						}
						if(data[i].cellphone == null || data[i].cellphone == undefined){
							data[i].cellphone = "";
						}
						
					}
					content += "<div class=\"data-trs-show\" indexs = '"+i+"'  lnglat = \""+data[i].lonLat+"\">" +
					"<div class=\"pdata-name\" style='width:190px;' title='"+data[i].studentname+"'>"+substr(data[i].studentname,8)+"</div>" +
					"<div class=\"pdata-class\" style='width:190px;'>" + data[i].cellphone + "</div>" +
					"<div class=\"pdata-add\" style='width:190px;' title=\""+data[i].address+"\">" + substr(data[i].address,12) + "</div>" +
					"</div>";
				}
				
				$(".left-datas-show").empty();
				$(".left-datas-show").append(content);
				
				$(".data-trs-show").click(function(){
					map.clearInfoWindow();
					var lonLat = $(this).attr("lnglat");
					if(lonLat != "undefined" && lonLat != undefined){
						var index = $(this).attr("indexs");
						var nowData = data[index];
						var pointArr = lonLat.split(",");
						var x = pointArr[0];
						var y = pointArr[1];
						var showObj = {};
						showObj["学生"] = nowData.studentname;
						showObj["IMEI"] = nowData.imei;
						showObj["数据时间"] = nowData.time;
						if(nowData.address != null){
							showObj["当前位置"] = nowData.address;
						}else{
							showObj["当前位置"] = "暂时不能定位到准确地点";
						}
						var imgUrl = "";
						if(nowData.type == 0 || nowData.type == "0"){
							imgUrl = '../../../../img/position/lixian.png';
							showObj["定位方式"] = "离线";
						}else if(nowData.type == 1 || nowData.type == "1"){
							imgUrl = '../../../../img/position/beidou.png';
							showObj["定位方式"] = "北斗定位";
						}else if(nowData.type == 2 || nowData.type == "2"){
							imgUrl = '../../../../img/position/shinei.png';
							showObj["定位方式"] = "蓝牙定位";
							var roomD = JSON.parse(nowData.remark);
							showObj["室内地图"] = "<a href='javascript:void(0);' onClick=\"enterRoom('"+roomD.scale+"','"+roomD.x+"','"+roomD.y+"','"+roomD.build_name + roomD.floor+"','"+roomD.build_id+"','"+roomD.floor+"','"+showObj["学生"]+"','"+showObj["手机"]+"');\" class='enter-room'>进入</a>";
						}else if(nowData.type == 3 || nowData.type == "3"){
							imgUrl = '../../../../img/position/jizhan.png';
							showObj["定位方式"] = "基站定位";
						}
						showObj["终端电量"] = "<img src='../../../../img/position/power_"+ nowData.power +".png' style='padding-top:5px;'/>";
						var icon = new AMap.Icon({
							size:new AMap.Size(40,40),//图标大小
							image:imgUrl,//大图地址
							imageSize:new AMap.Size(40,40)
						});
						addMarker2(y,x,icon,showObj,"high-icon");
						map.panTo(new AMap.LngLat(x,y));
						
					}else{
						processError("未查到位置数据！");
					}
				});
			}else{
				content += "<div class='no-res-show'>未查询到相关数据！</div>";
				$(".left-datas-show").empty();
				$(".left-datas-show").append(content);
			}
		}else{
			content += "<div class='no-res-show'>未查询到相关数据！</div>";
			$(".left-datas-show").empty();
			$(".left-datas-show").append(content);
		}
		processEnd("加载成功");
	}else{
		content += "<div class='no-res-show'>未查询到相关数据！</div>";
		$(".left-datas-show").empty();
		$(".left-datas-show").append(content);
		processError("加载失败");
	}
}
function enterRoom(scale,x,y,name,buildid,floor,stuname,stuphone){
	$(".index-dialog-cover",top.document).show();
	$(".room-map-dialog",top.document).show();
	var imgUrl = "schoolimg/"+buildid+"-"+floor.toUpperCase()+".jpg";
	new RoomMap.initMap($("#room-map",top.document),scale,imgUrl);
	if(stuphone == undefined || stuphone == "undefined"){
		stuphone = "";
	}
	RoomMap.addPoint(x,y,"img/img.png",{
		title:stuname,
		height:100,
		contents :"<div class='di-le-na'>姓名</div><div class='di-ri-va'>"+stuname+"</div>" +
		//"<div class='di-le-na'>电话号码</div><div class='di-ri-va'>"+stuphone+"</div>" +
		"<div class='di-le-na'>当前位置</div><div class='di-ri-va'>"+name.toUpperCase()+"</div>",
	});
}
var markers = [];
//添加点方法并注册线点击事件
function addMarker(x,y,icon,obj,name){
	if(pointMarker[name]){
		pointMarker[name].setMap(null);
	}
	pointMarker[name] = new AMap.Marker({
		id:name,
		position:new AMap.LngLat(y,x),
		icon:icon, //marker图标
		offset:{x:-20,y:-40} //相对于基点的位置
	});
	pointMarker[name].setMap(map);
	markers.push(pointMarker[name]);
    clickLayer(pointMarker[name],function(){
    	var content = "<table>";
	    for(key in obj){
	    	if(key == "数据时间"){
	    		if(obj[key].toString().indexOf("-") < 0){
	    			obj[key] = getSmpFormatDateByLong(parseInt(obj[key])*1000,true);
	    		}
	    	}
	        content += "<tr><td style='text-align: right;font-weight:700;width:40%;'>"+key+"：</td><td>"+obj[key]+"</td></tr>";
	    }
	    content += "</table>";
	    map.clearInfoWindow();
	    var inforWindow = new AMap.InfoWindow({
			offset:new AMap.Pixel(0,-26),
			content:content
		});
	    inforWindow.open(map,pointMarker[name].getPosition());
    });
}
function addMarker2(x,y,icon,obj,name){
	if(pointMarker[name]){
		pointMarker[name].setMap(null);
	}
	pointMarker[name] = new AMap.Marker({
		id:name,
		position:new AMap.LngLat(y,x),
		icon:icon, //marker图标
		offset:{x:-20,y:-40} //相对于基点的位置
	});
	pointMarker[name].setMap(map);
    clickLayer(pointMarker[name],function(){
    	var content = "<table>";
	    for(key in obj){
	    	if(key == "数据时间"){
	    		if(obj[key].toString().indexOf("-") < 0){
	    			obj[key] = getSmpFormatDateByLong(parseInt(obj[key])*1000,true);
	    		}
	    	}
	        content += "<tr><td style='text-align: right;font-weight:700;width:40%;'>"+key+"：</td><td>"+obj[key]+"</td></tr>";
	    }
	    content += "</table>";
	    map.clearInfoWindow();
	    var inforWindow = new AMap.InfoWindow({
			offset:new AMap.Pixel(0,-26),
			content:content
		});
	    inforWindow.open(map,pointMarker[name].getPosition());
    });
}
function clickLayer(layer,method){
	AMap.event.addListener(layer, "click", method);
}
function pageBtns(){
//	$("#last-page").click(function(){
//		if(currentPage > 1){
//			currentPage --;
//			getStudentsByClassCode(currentPage);
//		}else{
//			return false;
//		}
//	});
//	$("#next-page").click(function(){
//		if(currentPage < totalPage){
//			currentPage ++;
//			getStudentsByClassCode(currentPage,pageSize);
//		}else{
//			return false;
//		}
//	});
}
function substr(str,len){
	if(str != undefined){
		if(str.length > len){
			str = str.substring(0,len-2)+"...";
			return str;
		}else{
			return str;
		}
	}else{
		return "";
	}
}
function initPages(){
	var bodyRW = $("#aposition-body",parent.document).width() - $(".left-data-show").width();
	$("#map").width(bodyRW);
	
	$(".history-audio").width(bodyRW);
	
	var flagW = $(".history-audio").width() - 221;
	$(".history-audio-time").width(flagW);
	
	var leftDH = $(".left-data-show").height() - $(".left-search-data").height() - $(".left-datas-page").height() - 15;
	$(".left-datas-show").height(leftDH);
}